<template>
	<view class="layout-container">
		<view class="nav">
			<text>{{dataConfig.titleConfig.val}}</text>
			<view class="btn" @click="goMore(dataConfig.linkConfig.val)">
				更多<tui-icon name="arrowright" :size="15"></tui-icon>
			</view>
		</view>
		<view class="grid">
			<view v-for="(item, index) in newData" :key="index" :id="'media-' + index" @click="goDetail(item.url)"
				:class="['media-item', { 'full-width': index <topLength }]">
				<!-- 默认显示图片 -->
				<image v-if="!item.isPlaying" :src="item.img" class="media" mode="aspectFill"></image>
				<!-- 进入中间区域后播放视频 -->
				<!-- #ifdef H5 -->
				<view v-else :id="'video-' + index" :ref="'videoRef-'+index" ref="videoContainers"
					style="width: 100%;height: 100%;border-radius: 20rpx;"></view>
				<!-- #endif  -->
				<view class="title">
					{{item.name}}
				</view>
			</view>
		</view>
		<MyUseOut :showModal="isUseOut" @close="isUseOut=false" />
	</view>
</template>

<script>
	// #ifdef H5
	import Hls from "hls.js"
	import Dplayer from "dplayer"
	// #endif
	export default {
		name: "MyTwoLayout",
		props: {
			data: {
				type: Array,
				default: () => []
			},
			dataConfig: {
				type: Object,
				default: () => {}
			}
		},
		watch: {
			dataConfig: {
				handler(newVal) {

					// let list1 = this.transformList(this.dataConfig.menuBigConfig.list.map(v => v.info).flat(1))
					// let list2 = this.transformList(this.dataConfig.menuSmallConfig.list.map(v => v.info).flat(1))
					let list1 = this.transformList(this.dataConfig.menuBigConfig.list)
					let list2 = this.transformList(this.dataConfig.menuSmallConfig.list)

					// console.log(123, list1, list2);

					this.newData = [...list1, ...list2];
					this.topLength = list1.length;
					// console.log('0000', this.topLength);
				},
				deep: true,
				immediate: true
			}
		},
		data() {
			return {
				isUseOut: false,
				newData: [],
				topLength: 0,
			};
		},
		onLoad() {
			// 如果是从本页面的MyUseOut弹框进入三种增加次数的页面去了，并且成功后，再跳转到本页面要默认关闭弹窗
			uni.$on('closeModal', data => {
				this.isUseOut = data
			})
		},
		methods: {
			// 格式化数据
			transformList(list) {
				const transformedList = [];
				list.forEach(item => {
					const img = item.img;
					const info = item.info;
					for (let i = 0; i < info.length; i += 2) {
						if (i + 1 < info.length) {
							transformedList.push({
								img: img,
								name: info[i].value,
								url: info[i + 1].value
							});
						}
					}
				});
				return transformedList;
			},
			goDetail(url) {
				if (!uni.getStorageSync('infinite'))) {
					this.isUseOut = true
					return
				}
				// 必须调用ADDuser接口才会有viewsNum和useViewsNum值
				uni.navigateTo({
					url
				})
			},
			goMore(url) {
				uni.navigateTo({
					url
				})
			},
			handleScroll() {
				const query = uni.createSelectorQuery().in(this);
				const windowHeight = uni.getSystemInfoSync().windowHeight;

				this.newData.forEach((item, index) => {
					const id = `media-${index}`;
					query.select(`#${id}`).boundingClientRect((rect) => {
						if (rect) {
							const centerY = rect.top + rect.height / 2;
							const isCenter = centerY > windowHeight * 0.4 && centerY < windowHeight * 0.6;

							if (isCenter && !item.isPlaying) {
								this.$set(this.newData, index, {
									...item,
									isPlaying: true
								});
								this.$nextTick(() => {
									this.videos('video-' + index, item);
								});
							} else if (!isCenter && item.isPlaying) {
								this.$set(this.newData, index, {
									...item,
									isPlaying: false
								});
								if (this.videoPlayers[`video-${index}`]) {
									this.videoPlayers[`video-${index}`].destroy();
									delete this.videoPlayers[`video-${index}`];
								}
							}
						}
					}).exec();
				});
			},
			// 初始化播放器
			videos(idSelector, item) {
				const container = document.getElementById(idSelector);
				if (container) {
					let dp = new Dplayer({
						container: container,
						autoplay: true, // 是否自动播放
						theme: "#000", // 主题色
						loop: false, // 视频是否循环播放
						lang: "zh-cn",
						airplay: true,
						screenshot: false, // 是否开启截图
						hotkey: false, // 是否开启热键
						preload: "metadata", // 视频是否预加载
						volume: 0, // 默认音量
						mutex: true, // 阻止多个播放器同时播放，当前播放器播放时暂停其他播放器
						controls: false, // 不显示控件
						video: {
							url: item.video,
							pic: item.img,
							type: 'customHls',
							customType: {
								customHls: function(video, player) {
									const hls = new Hls({
										maxBufferLength: 60,
										maxBufferSize: 300 * 1024 * 1024,
										maxBufferHole: 0.5,
										nudgeMaxRetry: 3,
										startFragPrefetch: true,
									});
									hls.loadSource(video.src);
									hls.attachMedia(video);
								},
							},

						}
					});
					dp.play();
					this.videoPlayers[idSelector] = dp;
				}
			},
		}
	}
</script>

<style lang="scss" scoped>
	.layout-container {
		width: 100%;
		margin: 20rpx 0;
	}

	/* 网格布局 */
	.grid {
		display: grid;
		grid-template-columns: repeat(2, 1fr);
		/* 默认2列 */
		gap: 0 10px;
		/* width: 100%; */
	}

	.title {
		text-align: center;
		margin: 8rpx 0;
	}

	.nav {
		display: flex;
		justify-content: space-between;
		margin-bottom: 10rpx;

		.btn {
			padding: 8rpx 26rpx 8rpx 40rpx;
			font-size: 22rpx;
			display: flex;
			color: #999999;
			align-items: center;
			border: 2rpx solid #a6a6a6;
		}
	}

	/* 默认的媒体项样式 */
	.media-item {
		width: 100%;
		height: 230rpx;
		flex-direction: column;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	/* 图片和视频 */
	.media {
		width: 100%;
		height: 100%;
		border-radius: 15rpx;
		object-fit: cover;
	}

	/* 前三项独占一行 */
	.full-width {
		height: 360rpx;

		grid-column: span 2;
		/* 跨 2 列 */
	}
</style>